package com.lm.scau.dyb.activity.base;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.lm.scau.dyb.R;
import com.lm.scau.dyb.bean.PackageBean;
import com.lm.scau.dyb.fragment.TitleFragment;
import com.lm.scau.dyb.inter.BasicUIEvent;
import com.lm.scau.dyb.inter.HttpExecuteEvent;
import com.lm.scau.dyb.inter.UICore;
import com.lm.scau.dyb.utils.HttpUtils;
import com.lm.scau.dyb.utils.MD5Util;
import com.lm.scau.dyb.utils.PhoneUtil;
import com.lm.scau.dyb.utils.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Function:
 * auth：liming on 2016/8/15 14:22
 * mail：liming@wxchina.com
 */
public class RegisterActivity extends BaseActivity implements HttpExecuteEvent, BasicUIEvent, Handler.Callback {
    private static final int MSG_WAIT_CODE = 10;
    private TitleFragment titleFragment;
    private TextView accountView;
    private TextView phoneView;
    private TextView codeView;
    private TextView pwdView;
    private TextView pwdCommitView;
    private Button btnRegister;
    private Button btnGetCode;
    private Handler handler;
    private boolean stopWaitCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        initAction();
        handler = new Handler(this);
    }

    private void initAction() {
        btnGetCode.setOnClickListener(new mClickListerner());
        btnRegister.setOnClickListener(new mClickListerner());
    }

    private void initView() {
        titleFragment = (TitleFragment) getSupportFragmentManager().findFragmentById(R.id.title_fragment);
        titleFragment.initTitle(false, true, "注册");
        accountView = (TextView) findViewById(R.id.text_view_account);
        phoneView = (TextView) findViewById(R.id.text_view_phone);
        codeView = (TextView) findViewById(R.id.text_view_code);
        pwdView = (TextView) findViewById(R.id.text_view_pwd);
        pwdCommitView = (TextView) findViewById(R.id.text_view_pwd_commit);
        btnGetCode = (Button) findViewById(R.id.btn_get_code);
        btnRegister = (Button) findViewById(R.id.btn_register);
    }

    @Override
    public void onResponeSuccess(String respone) {
        System.out.print("register: " + respone);
        try {
            JSONObject obj = new JSONObject(respone);
            String method = obj.getString("method");
            JSONObject cont = obj.getJSONObject("cont");
            switch (method) {
                case "sendCodeToSMS":
                    String code = cont.getString("code");
                    if ("0".equals(code)) { //
                        showToast("验证码发送成功，请注意接收...");
                        btnGetCode.setEnabled(false);
                        UICore.eventTask(this, this, MSG_WAIT_CODE, null, null, false);
                    } else if ("111111".equals(code)) {
                        showToast("手机号码已经注册过，请直接登陆...");
                    }
                    break;
                case "userRegister":
                    String msg = cont.getString("msg");
                    if ("注册成功".equals(msg)) { //注册成功，直接返回我的页面
                        startActivity(LoginActivity.class,null);
                        this.finish();
                    }
                    showToast(msg);
                    break;
                default:
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResponeError(String respone) {
        showToast("连接服务器失败...");
    }

    private boolean checkPhone() {
        boolean legal = PhoneUtil.isMobileNO(phoneView.getText().toString().replace(" ", ""));
        if (!legal) {
            showToast("手机号码格式不正确，请重新输入.");
        }
        return legal;
    }

    private boolean checkLegal() {
        if (!pwdView.getText().toString().equals(pwdCommitView.getText().toString())) {
            showToast("两次密码输入不一致.");
            return false;
        }
        if (!checkPhone()) {
            showToast("手机号码格式不正确，请重新输入.");
            return false;
        }
        if ("".equals(accountView.getText().toString().trim()) || "".equals(phoneView.getText().toString().trim()) || "".equals(codeView.getText().toString().trim()) || "".equals(pwdView.getText().toString().trim()) || "".equals(pwdCommitView.getText().toString().trim())) {
            showToast("信息填写不完整，请填写完整.");
            return false;
        }
        return true;
    }

    @Override
    public void execute(int msg, Object obj) {
        switch (msg) {
            case MSG_WAIT_CODE:
                waitToGetCode();
                break;
            default:
                break;
        }
    }

    //倒计时获取验证码2分钟
    private void waitToGetCode() {
        int second = 120;
        stopWaitCode = true;
        while (stopWaitCode && second > -1) {
            try {
                Message msg = Message.obtain(handler, MSG_WAIT_CODE, second);
                msg.sendToTarget();
                Thread.sleep(1000);
                second--;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        btnGetCode.setText("获取验证码");
        btnGetCode.setEnabled(true);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_WAIT_CODE:
                btnGetCode.setText("剩余：" + msg.obj + "s");
                break;
            default:
                break;
        }
        return false;
    }

    class mClickListerner implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_get_code:
                    //发送get请求服务器，取得验证码
                    if (checkPhone()) {
                        JSONObject cont = new JSONObject();
                        try {
                            cont.put("phone", phoneView.getText().toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        PackageBean pk = new PackageBean();
                        pk.msgname = "UserAction";
                        pk.method = "sendCodeToSMS";
                        pk.cont = cont;
                        httpUtils.httpRequestGet(pk.toString(), true, (RegisterActivity) mActivity);
                    }
                    break;
                case R.id.btn_register:
                    if (checkLegal()) {
                        PackageBean pk = new PackageBean();
                        JSONObject cont = new JSONObject();
                        pk.msgname = "UserAction";
                        pk.method = "userRegister";
                        try {
                            cont.put("pwd", MD5Util.string2MD5(pwdView.getText().toString()));
                            cont.put("Name", StringUtils.parseCn(accountView.getText().toString()));
                            cont.put("phone", phoneView.getText().toString());
                            cont.put("code", codeView.getText().toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        pk.cont = cont;
                        System.out.print(pk.toString());
                        httpUtils.httpRequestGet(pk.toString(), true, (RegisterActivity) mActivity);
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
